import { injectable } from "@theia/core/shared/inversify";
import { ITestServer, ResBody } from "../common/test-control";
import { Worker } from 'worker_threads';
const CppExtension = require('cpp-extension');

@injectable()
export class TestServerImpl implements ITestServer {
    async isAlive(): Promise<string> {
        return CppExtension.ServerIsAlive();
    }

    async cppDoLongTask(reqId:string): Promise<ResBody> {
        return new Promise(resolve => {
            // 传递请求ID
            CppExtension.DoLongTask(reqId, (resId: string, status: number, data: string) => {
                switch (status) {
                    case 0:
                        console.log('c++ receive request');
                        break;
                    case 1:
                        console.log(data);
                        break;
                    case 2: // 只有status 是 2 时c++执行结束 返回数据给前台
                        resolve({ resId, data });
                        return;
                }
            });
        });
    }

    async nodeDoLongTask(reqId: string): Promise<ResBody> {
        return new Promise(resolve => {
            // 启动线程
            const worker = new Worker(__dirname + '/do-long-task.js', { workerData: reqId });
            // 收到消息并返回
            worker.on('message', ([resId, status, data]) => {
                switch (status) {
                    case 0:
                        console.log('c++ receive request');
                        break;
                    case 1:
                        console.log(data);
                        break;
                    case 2: // 只有status 是 2 时c++执行结束 返回数据给前台
                        resolve({resId, data});
                        return;
                }
            });
        });
    }
}

